package com.poisonh.unifiedauth.ui;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.CardView;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import com.lzy.okhttputils.model.HttpParams;
import com.poisonh.unifiedauth.R;
import com.poisonh.unifiedauth.dialog.AddCardDialogFragment;
import com.poisonh.unifiedauth.dialog.AuthDialogFragment;
import com.poisonh.unifiedauth.dialog.OtherInfoDialogFragment;
import com.poisonh.unifiedauth.dialog.SDKAuthDialogFragment;
import com.poisonh.unifiedauth.dialog.SignOutDialogFragment;
import com.poisonh.unifiedauth.dialog.UpdateDialogFragment;
import com.poisonh.unifiedauth.dialog.UserCardDialogFragment;
import com.poisonh.unifiedauth.dialog.UserInfoDialogFragment;
import com.poisonh.unifiedauth.model.BusinessCard;
import com.poisonh.unifiedauth.model.IdCard;
import com.poisonh.unifiedauth.service.DownLoadService;
import com.poisonh.unifiedauth.utils.ActivityStack;
import com.poisonh.unifiedauth.utils.ConstantUitls;
import com.poisonh.unifiedauth.utils.ExampleUtil;
import com.poisonh.unifiedauth.utils.GlideCircleTransform;
import com.poisonh.unifiedauth.utils.ImageUtils;
import com.poisonh.unifiedauth.utils.MyHttpsUtils;
import com.poisonh.unifiedauth.utils.PreferencesUtils;
import com.poisonh.unifiedauth.utils.ToastUtils;
import com.poisonh.unifiedauth.widget.MainPopupWindow;
import com.poisonh.unifiedauth.widget.ResideMenu;
import com.poisonh.unifiedauth.widget.ResideMenuItem;
import com.poisonh.unifiedauth.widget.RingView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import io.realm.Realm;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 主界面
 * Created by PoisonH on 2016/6/21.
 */
public class MainActivity extends BaseActivity implements View.OnClickListener,UpdateDialogFragment.UpdateAppListener {

    //  private static final String TAG = "JPush";
    private ResideMenu resideMenu;
    private ProgressDialog progressDlg;
    private MainActivity mContext;
    private ResideMenuItem itemHeadImage;
    private ResideMenuItem itemPhone;
    private ResideMenuItem itemUserInfo;
    private ResideMenuItem itemSecuritySetting;
    private ResideMenuItem itemAbout;//关于
    private ResideMenuItem itemExite;
    private RingView mRvRingView;
    private String mStrDownLoadUrl;

    private LinearLayout mLLScan;
    private LinearLayout mLLMyInfo;
    private LinearLayout mLLCertificationManagement;
    private LinearLayout mLLFind;

    private RelativeLayout mLayout;

    private Button mBtnPromoteCredit;
    private ImageButton mIBtnInfoShare;
    private ImageButton mIBtnInfoCenter;
    private ImageButton mIBtnUserInfo;
    private TextView mTvInfoCount;

    private TextView mUnVerity;
    private TextView mName;
    private TextView mCellphone;
    private TextView mEMail;
    private TextView mCompany;

    private ImageView mCellphoneImg;
    private ImageView mEMailImg;
    private ImageView mCompanyImg;

    private ImageView mMyHead;

    private RequestManager glideRequest;

    private CardView card_view;

    private ImageView head_imgcard;
    //private String CompareImg;


    private BusinessCard mBusinessCard;
    private IdCard mIdCard;
    private String mStrPhone;
    private String mStrScore;
    private String mStrHeadUrl;
    private static int mInfoCount = 0;
    private String msg;

    //for receive customer msg from jpush server
    private MessageReceiver mMessageReceiver;
    public static final String KEY_TITLE = "title";
    public static final String KEY_MESSAGE = "message";
    public static final String KEY_EXTRAS = "extras";
    public static final String MESSAGE_ACTION_AUTH_LOGIN = "com.example.jpushdemo.MESSAGE_ACTION_AUTH_LOGIN";
    public static final String MESSAGE_ACTION_INFO = "com.example.jpushdemo.MESSAGE_ACTION_INFO";
    public static final String MESSAGE_ACTION_AUTHORIZATION = "com.example.jpushdemo.MESSAGE_AUTHORIZATION";
    public static boolean isForeground = false;
    private static final int MSG_SET_ALIAS = 1001;

    private Button btAddCard;

    //第一次加载页面
    private boolean firstLoad = true;
    private boolean is_show=true;

    //第一次显示数据
//    private boolean firstShowDialog = true;
    private View rootView;
    private MainPopupWindow popupWindow;
    private TextView head_name;

    @Override
    protected void loadContentView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_main);
        rootView = LayoutInflater.from(this).inflate(R.layout.activity_main, null);
        mLayout = (RelativeLayout) findViewById(R.id.layout);
        mLayout.setVisibility(View.GONE);
        mStrPhone = getIntent().getStringExtra("PHONE");
        checkSDK();
        getHeadUrl();
        initView();
        mContext = this;
        updateApp();
//        checkUserAllInfo();
       // updatefile();
    }


    /**
     * 发短信
     */
    private void sendSMS(String webUrl) {
        String smsBody = "姓名: " + ((TextView) findViewById(R.id.name)).getText().toString() + "\n" +
                "手机: " + ((TextView) findViewById(R.id.cellphone)).getText().toString() + "\n" +
                "邮箱: " + ((TextView) findViewById(R.id.email)).getText().toString() + "\n" +
                "地址: " + ((TextView) findViewById(R.id.company)).getText().toString() + "\n" +
                "年轮，您的身份管理专家！" + "\n" +
                webUrl;
        Uri smsToUri = Uri.parse("smsto:");
        Intent sendIntent = new Intent(Intent.ACTION_VIEW, smsToUri);
        //sendIntent.putExtra("address", "123456"); // 电话号码，这行去掉的话，默认就没有电话
        //短信内容
        sendIntent.putExtra("sms_body", smsBody);
        sendIntent.setType("vnd.android-dir/mms-sms");
        startActivityForResult(sendIntent, 1002);
    }

    private void checkSDK() {
        if (!TextUtils.isEmpty(ConstantUitls.SDK_APPID) && !TextUtils.isEmpty(ConstantUitls.SDK_APPNAME) && !TextUtils.isEmpty(ConstantUitls.SDK_APPIMG)) {
            SDKAuthDialogFragment sdkAuthDialogFragment = new SDKAuthDialogFragment();
            sdkAuthDialogFragment.show(getFragmentManager(), "");
        }
    }

    private void getHeadUrl() {
//        //根据id查询用户
//        UserinfoDaoImpl mUserinfoDaoImpl = new UserinfoDaoImpl(MainActivity.this);
//        try
//        {
//            UserInfoModel model = mUserinfoDaoImpl.queryReturnOne(mStrUserId);
//            mStrHeadUrl = model.getmStrHeadUrl();
//            mUserinfoDaoImpl.commit();
//        } catch (Exception e)
//        {
//            e.printStackTrace();
//        }

        Realm realm = Realm.getDefaultInstance();
        mBusinessCard = realm.where(BusinessCard.class).equalTo("uid", mStrUserId).findFirst();
        realm.close();
        if (mBusinessCard != null) {
            mStrHeadUrl = ConstantUitls.REQUEDT_IMG_URL + mBusinessCard.getHeadImg();
        } else {
            mStrHeadUrl = ConstantUitls.REQUEDT_IMG_URL + ConstantUitls.DEFAULTHEADIMG;
        }
    }

    /**
     * 初始化视图
     */
    protected void initView() {
        registerMessageReceiver();
        setAlias();

        // mRvRingView = (RingView) findViewById(R.id.rv_ringview);
        btAddCard = (Button) findViewById(R.id.bt_add_card);
        head_imgcard = (ImageView) findViewById(R.id.head_img1);
        card_view = (CardView) findViewById(R.id.card_view);
        card_view.setDrawingCacheEnabled(true);

        //头像的点击事件
        head_imgcard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBusinessCard != null) {
                    if(popupWindow==null){
                        popupWindow = new MainPopupWindow(MainActivity.this, mBusinessCard, mStrUserId,mStrUserToken);
                    }
                    if(popupWindow.isShowing()==true){
                        popupWindow.dismiss();
                    }else if(popupWindow.isShowing()==false){
                        popupWindow.show(rootView,mBusinessCard);

                    }
                } else {
                    Intent setHeadIntent = new Intent(MainActivity.this, SettingCardActivity.class);// 注册流程增加头像
                    setHeadIntent.putExtra("code", "1");
                    setHeadIntent.putExtra("PHONE", mStrPhone);
                    startActivity(setHeadIntent);
                    overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
                }
            }
        });

        head_name = (TextView) findViewById(R.id.head_name);//主界面头像下面的名字

        mLLScan = (LinearLayout) findViewById(R.id.ll_scan);
        mLLMyInfo = (LinearLayout) findViewById(R.id.ll_myinfo);
        mLLCertificationManagement = (LinearLayout) findViewById(R.id.ll_certification_management);
        mLLFind = (LinearLayout) findViewById(R.id.ll_find);
//        mBtnPromoteCredit = (Button) findViewById(R.id.btn_promote_credit);
        mIBtnInfoCenter = (ImageButton) findViewById(R.id.ib_info);
      //  mIBtnInfoShare = (ImageButton) findViewById(R.id.ib_share);//原分享按钮
        mIBtnUserInfo = (ImageButton) findViewById(R.id.ib_userinfo);
        mTvInfoCount = (TextView) findViewById(R.id.tv_info_count);//消息提示
        mIBtnInfoCenter.setOnClickListener(this);

//        mBtnPromoteCredit.setOnClickListener(this);
        mLLScan.setOnClickListener(this);
        mLLMyInfo.setOnClickListener(this);
        mLLCertificationManagement.setOnClickListener(this);
        mLLFind.setOnClickListener(this);
        mIBtnUserInfo.setOnClickListener(this);
        btAddCard.setOnClickListener(this);

        mUnVerity = (TextView) findViewById(R.id.verify);

        //初始化侧滑菜单
        setUpMenu();

//        initRingView();
//        mRvRingView.setPointer(false);

        mInfoCount = PreferencesUtils.getInt(this, "INFO_COUNT");
        if (mInfoCount > 0) {
            mTvInfoCount.setVisibility(View.VISIBLE);
            mTvInfoCount.setText(mInfoCount + "");
        } else {
            mInfoCount = 0;

        }

        mUnVerity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                startActivity(new Intent(MainActivity.this, IdentityCardActivity.class));
            }
        });

    }

    private void setUpMenu() {
        // attach to current activity;
        resideMenu = new ResideMenu(this);
        resideMenu.setUse3D(true);
        //设置背景
        resideMenu.setBackground(R.mipmap.menu_background);
        resideMenu.attachToActivity(this);
        //valid scale factor is between 0.0f and 1.0f. leftmenu'width is 150dip.
        resideMenu.setScaleValue(0.6f);

        // create menu items;


//        if ((mStrHeadUrl != null && mStrHeadUrl.length() > 0))
//        {
//            itemHeadImage = new ResideMenuItem(mStrHeadUrl, mStrUserName != null ? mStrUserName : mStrUserPhone, this);
//        } else
//        {
//            itemHeadImage = new ResideMenuItem(this, R.drawable.headimage, mStrUserName != null ? mStrUserName : mStrUserPhone);
//        }

        if (mBusinessCard != null) {
            itemHeadImage = new ResideMenuItem(ConstantUitls.REQUEDT_IMG_URL + mBusinessCard.getHeadImg(), mBusinessCard.getName(), this);
        } else {
            itemHeadImage = new ResideMenuItem(ConstantUitls.REQUEDT_IMG_URL + ConstantUitls.DEFAULTHEADIMG, mStrHeadUrl, this);
        }
//
//        String title = mStrUserName != null ? mStrUserName : mStrPhone;

//        if (mStrUserName != null && mStrUserName.length() > 0)
//        {
//            itemPhone = new ResideMenuItem(this, mStrUserName);
//        } else
//        {
//            itemPhone = new ResideMenuItem(this, mStrPhone);
//        }

        //  itemPhone = new ResideMenuItem(this, mStrPhone);
        itemUserInfo = new ResideMenuItem(this, "身份管理");
        itemSecuritySetting = new ResideMenuItem(this, "安全设置");
        itemAbout = new ResideMenuItem(this, "关于");
        itemExite = new ResideMenuItem(this, "退出");

        itemUserInfo.setOnClickListener(this);
        itemSecuritySetting.setOnClickListener(this);
        itemAbout.setOnClickListener(this);
        itemExite.setOnClickListener(this);
        itemHeadImage.setOnClickListener(this);

        //itemHeadImage.registerChangeHeadBR();
        // itemPhone.registerChangeHeadBR();

        resideMenu.addMenuItem(itemHeadImage, ResideMenu.DIRECTION_LEFT);
        // resideMenu.addMenuItem(itemPhone, ResideMenu.DIRECTION_LEFT);
        resideMenu.addMenuItem(itemUserInfo, ResideMenu.DIRECTION_LEFT);
        resideMenu.addMenuItem(itemSecuritySetting, ResideMenu.DIRECTION_LEFT);
        resideMenu.addMenuItem(itemAbout, ResideMenu.DIRECTION_LEFT);
        resideMenu.addMenuItem(itemExite, ResideMenu.DIRECTION_LEFT);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        return resideMenu.dispatchTouchEvent(ev);
    }

    /**
     * 点击事件
     *
     * @param view
     */
    @Override
    public void onClick(View view) {

        if (view == itemUserInfo) {
            //startActivity(new Intent(MainActivity.this, SettingShouMyinfoActivity.class));
            startActivity(new Intent(MainActivity.this, IdentityCardActivity.class));
        }
        if (view == itemHeadImage) {
            //startActivity(new Intent(MainActivity.this, SettingHeadImgActivity.class));
            if (mIdCard != null) {
                if (mIdCard.getCert() == 1) {
                    startActivity(new Intent(MainActivity.this, SettingCardActivity.class));
                }
            }

        }
        if (view == itemSecuritySetting) {
            startActivity(new Intent(MainActivity.this, SettingSecurityActivity.class));
        }
        if (view == itemAbout) {
            startActivity(new Intent(MainActivity.this, AboutActivity.class));
        }
        if (view == itemExite) {
            SignOutDialogFragment fragment = new SignOutDialogFragment();//退出登录的DialogFragment
            fragment.show(getFragmentManager(), "");
        }


        switch (view.getId()) {
            case R.id.ll_scan:
                startActivityForResult(new Intent(MainActivity.this, ScanQRCodeActivty.class), 0);
                break;
            case R.id.ll_myinfo:
                Intent mIntent = new Intent(MainActivity.this, MyInfoActivity.class);
//                mIntent.putExtra("SCORE", mStrScore);
                startActivity(mIntent);
                break;
            case R.id.ll_find:
                startActivity(new Intent(MainActivity.this, FindActivity.class));
                break;
//            case R.id.btn_promote_credit:
//                startActivity(new Intent(MainActivity.this, SettingUpLevelActivity.class));
//                break;
            case R.id.ll_certification_management://身份管理点击事件
                //  startActivity(new Intent(MainActivity.this, CertificationManagementActivity.class));
                startActivity(new Intent(MainActivity.this, IdentityCardActivity.class));
                break;
            case R.id.ib_info:
                startActivity(new Intent(MainActivity.this, InfoCenterActivity.class));
                PreferencesUtils.deleteValue(this, "INFO_COUNT");
                mInfoCount = 0;
                mTvInfoCount.setVisibility(View.GONE);
                break;
            case R.id.ib_userinfo:
                resideMenu.openMenu(ResideMenu.DIRECTION_LEFT);
                break;
            case R.id.bt_add_card:
//                Intent setHeadIntent = new Intent(MainActivity.this, SettingCardActivity.class);// 注册流程增加头像
//                setHeadIntent.putExtra("code", "1");
//                setHeadIntent.putExtra("PHONE", mStrPhone);
//                startActivity(setHeadIntent);
//                overridePendingTransition(R.anim.fade_in, R.anim.fade_out);


                if (mIdCard != null) {
                    Intent setHeadIntent = new Intent(MainActivity.this, CameraActivity.class);// 注册流程增加头像
                    startActivity(setHeadIntent);
                } else {
                    Intent addIdCardIntent = new Intent(MainActivity.this, IdCardSettingActivity.class);// 新增身份证信息
                    startActivity(addIdCardIntent);

                }
                overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
                //  finish();
                break;
        }
    }

    /**
     * activity返回结果处理
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == ScanQRCodeActivty.SCAN_RESULT_AUTHTHIRDAPP_MARK) {
            Bundle bundle = data.getExtras();
            AuthDialogFragment authDialogFragment = new AuthDialogFragment();
            authDialogFragment.setArguments(bundle);
            authDialogFragment.show(getFragmentManager(), "");
        }
        if (resultCode == ScanQRCodeActivty.SCAN_RESULT_AUTHMYAPP_MARK) {
            Bundle bundle = data.getExtras();
            UserInfoDialogFragment userinfoDialogFragment = new UserInfoDialogFragment();
            userinfoDialogFragment.setArguments(bundle);
            userinfoDialogFragment.show(getFragmentManager(), "");
        }
        if (resultCode == ScanQRCodeActivty.SCAN_RESULT_OTHERRESULTS_MARK) {
            Bundle bundle = data.getExtras();
            OtherInfoDialogFragment otherinfoDialogFragment = new OtherInfoDialogFragment();
            otherinfoDialogFragment.setArguments(bundle);
            otherinfoDialogFragment.show(getFragmentManager(), "");
        }
        if (resultCode == ScanQRCodeActivty.SCAN_RESULT_CARD_MARK) {
            Bundle bundle = data.getExtras();
            UserCardDialogFragment cardinfoDialogFragment = new UserCardDialogFragment();
            cardinfoDialogFragment.setArguments(bundle);
            cardinfoDialogFragment.show(getFragmentManager(), "");
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        isForeground = true;
        Log.d("AAA", "onResume()");
        checkUserAllInfo();
    }

    private void setAlias() {
        if (TextUtils.isEmpty(mStrUserId)) {
            Log.d("MainActivity", "alias不能为空");
            return;
        }
        if (!ExampleUtil.isValidTagAndAlias(mStrUserId)) {
            Log.d("MainActivity", "格式不对");
            return;
        }

        //调用JPush API设置Alias
        mAliasHandler.sendMessage(mAliasHandler.obtainMessage(MSG_SET_ALIAS, mStrUserId));
    }

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {

        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    Log.d("JPush", logs);
                    break;

                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    Log.d("JPush", logs);
                    if (ExampleUtil.isConnected(getApplicationContext())) {
                        mAliasHandler.sendMessageDelayed(mAliasHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
                    } else {
                        Log.d("JPush", "No network");
                    }
                    break;

                default:
                    logs = "Failed with errorCode = " + code;
                    Log.d("JPush", logs);
            }

            //ToastUtils.showToast(getApplicationContext(), logs);
        }

    };


    Handler mAliasHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                case MSG_SET_ALIAS:
                    Log.d("JPush", "Set alias in handler.");
                    JPushInterface.setAliasAndTags(getApplicationContext(), (String) msg.obj, null, mAliasCallback);
                    break;
            }
        }
    };

    public void registerMessageReceiver() {
        mMessageReceiver = new MessageReceiver();
        IntentFilter filter = new IntentFilter();
        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        filter.addAction(MESSAGE_ACTION_INFO);
        filter.addAction(MESSAGE_ACTION_AUTH_LOGIN);
//        filter.addAction(MESSAGE_ACTION_AUTHORIZATION);
        registerReceiver(mMessageReceiver, filter);
    }

    public class MessageReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String messge = intent.getStringExtra(KEY_MESSAGE);
            String extras = intent.getStringExtra(KEY_EXTRAS);
            String app_id = "null";
            String uuid = "null";
            String app_name = "null";
            String app_img = "null";

            try {
                JSONObject object = new JSONObject(messge);
                msg=object.getString("msg");//入所扫描商户名称
                JSONObject data = object.getJSONObject("results");
                app_id = data.getString("app_id");
                uuid = data.getString("uuid");
                app_name = data.getString("app_name");
                app_img = data.getString("app_img");

            } catch (JSONException e) {
                e.printStackTrace();
            }
            if (MESSAGE_ACTION_INFO.equals(intent.getAction())) {
                Message msg = Message.obtain();
                msg.what = 1;
                mHandler.sendMessage(msg);
            }
            if (MESSAGE_ACTION_AUTH_LOGIN.equals(intent.getAction())) {

                Bundle mBundle = new Bundle();
                mBundle.putString("app_id", app_id);
                mBundle.putString("uuid", uuid);
                mBundle.putString("app_name", app_name);
                mBundle.putString("app_img", app_img);

                AuthDialogFragment authDialogFragment = new AuthDialogFragment();
                authDialogFragment.setArguments(mBundle);
                authDialogFragment.show(getFragmentManager(), "");
            }
//            if(MESSAGE_ACTION_AUTHORIZATION.equals(intent.getAction())){
//                MerchantsDialogFragment merchantsDialogFragment=new MerchantsDialogFragment();
//                Bundle mBundle = new Bundle();
//                mBundle.putString("msg",msg);
//                merchantsDialogFragment.setArguments(mBundle);
//                merchantsDialogFragment.show(getFragmentManager(), "");
//            }
        }
    }

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                case 1:
                    mInfoCount = mInfoCount + 1;
                    mTvInfoCount.setVisibility(View.VISIBLE);
                    mTvInfoCount.setText(mInfoCount + "");
                    break;
                case 2:
                    try {
                        JSONObject object = new JSONObject(msg.obj.toString());
                        JSONObject data = object.getJSONObject("results");
                        mStrScore = data.getString("score");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                case 3:  //数据同步后获取明片
                    checkUserAllInfo();
                    break;
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (mInfoCount > 0) {
            PreferencesUtils.putInt(this, "INFO_COUNT", mInfoCount);
        }
        unregisterReceiver(mMessageReceiver);
        //itemHeadImage.unRegisterChangeHeadBR();
        //itemPhone.unRegisterChangeHeadBR();
        ActivityStack.getAppManager().finishActivity(this);
    }

    //监听返回事件的方法
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mInfoCount > 0) {
                PreferencesUtils.putInt(this, "INFO_COUNT", mInfoCount);

            } else if (popupWindow != null && popupWindow.isShowing() == true) {


                popupWindow.dismiss();
                return true;
            } else if (popupWindow != null && popupWindow.isShowing() == false) {
                ActivityStack.getAppManager().exit();
                //杀死该应用进程
                android.os.Process.killProcess(android.os.Process.myPid());
            }

        }

        return super.onKeyDown(keyCode, event);
    }

    /**
     * 查看用户所有信息 绑定数据
     */
    private void checkUserAllInfo() {
        Realm realm = Realm.getDefaultInstance();
        mBusinessCard = realm.where(BusinessCard.class).equalTo("uid", mStrUserId).findFirst();
        mIdCard = realm.where(IdCard.class).equalTo("uid", mStrUserId).findFirst();
        List list = realm.where(BusinessCard.class).equalTo("uid", mStrUserId).findAll();

        realm.close();
        if (null == mIdCard) {
            if (!firstLoad) { //只加载一次
                AddCardDialogFragment fragment = new AddCardDialogFragment();
                fragment.show(getFragmentManager(), "");
            }
        }
        if (null == mBusinessCard) { //手机没有完整信息
            if (mIdCard != null && mIdCard.getCert() == 1) {
                itemHeadImage.setTitle(mIdCard.getName());
                if (mIdCard.getCompareImg() != null) {

                    Glide.with(this).load(ConstantUitls.REQUEDT_IMG_URL + mIdCard.getCompareImg()).transform(new GlideCircleTransform(this)).into(head_imgcard);//加载圆角图片
                    itemHeadImage.setImg(ConstantUitls.REQUEDT_IMG_URL + mIdCard.getCompareImg());//侧滑头像
                    updatefile();//下载头像图片
                }
                btAddCard.setVisibility(View.GONE);
                head_imgcard.setVisibility(View.VISIBLE);//新添加的头像
                head_name.setText(mIdCard.getName());
                head_name.setVisibility(View.VISIBLE);

            } else {
                itemHeadImage.setTitle(mStrPhone);
                itemHeadImage.setImg(ConstantUitls.REQUEDT_IMG_URL + ConstantUitls.DEFAULTHEADIMG);
                Glide.with(this).load(ConstantUitls.REQUEDT_IMG_URL + ConstantUitls.DEFAULTHEADIMG).transform(new GlideCircleTransform(this)).into(head_imgcard);//加载圆角图片默认头像

                if (firstLoad) { //只加载一次 //第一次加载页面
                    firstLoad = false;
                    sycAllUserInfo();
                } else {
                    btAddCard.setVisibility(View.VISIBLE);
                    head_imgcard.setVisibility(View.GONE);//新添加的头像
                    head_name.setVisibility(View.GONE);
                }
            }

        } else {
            showBusinessCard();//显示名片夹
            itemHeadImage.setTitle(mBusinessCard.getName());
            itemHeadImage.setImg(ConstantUitls.REQUEDT_IMG_URL + mBusinessCard.getHeadImg());
            btAddCard.setVisibility(View.GONE);
            head_imgcard.setVisibility(View.VISIBLE);//新添加的头像

            Glide.with(this).load(ConstantUitls.REQUEDT_IMG_URL + mBusinessCard.getHeadImg()).transform(new GlideCircleTransform(this))
                    .into(head_imgcard);//加载圆角图片
            head_name.setText(mBusinessCard.getName());
            head_name.setVisibility(View.VISIBLE);
            updatefile();//下载头像图片
        }
    }

    /**
     * 同步当前用户所有信息 除用户表 , 现在包含身份证 明信片 表
     */
    private void sycAllUserInfo() {

        HttpParams params = new HttpParams();

        params.put("userId", mStrUserId);
        params.put("token", mStrUserToken);

        MyHttpsUtils.post(ConstantUitls.REQUEDT_URL + ConstantUitls.GETUSERALLINFO, params, new MyHttpsUtils.ResultCallback() {
            @Override
            public void onSuccess(String response) {
                JSONObject resultsJson = null;
                Realm realm = null;
                try {
                    JSONObject responseJson = new JSONObject(response);
                    resultsJson = responseJson.getJSONObject("results");
                    realm = Realm.getDefaultInstance();
                    realm.beginTransaction();
                    if (resultsJson.has("idCards")) {
                        JSONArray idCards = resultsJson.getJSONArray("idCards");
                        if (idCards.length() > 0) {
                            realm.createOrUpdateAllFromJson(IdCard.class, idCards);
                        }
                    }
                    if (resultsJson.has("businessCards")) {
                        JSONArray businessCards = resultsJson.getJSONArray("businessCards");
                        if (businessCards.length() > 0) {
                            realm.createOrUpdateAllFromJson(BusinessCard.class, businessCards);
                        }
                    }
                    realm.commitTransaction();
                } catch (JSONException e) {
                    e.printStackTrace();
                } finally {
                    if (realm != null) {
                        realm.close();
                    }
                }
                //ToastUtils.showToast(MainActivity.this, "数据同步成功");
              //  progressDlg.dismiss();
              //  SVProgressHUD.dismiss(MainActivity.this);
                Message msg = Message.obtain();
                msg.what = 3;
                mHandler.sendMessage(msg);
            }

            @Override
            public void onFailure(String failReason) {
                btAddCard.setVisibility(View.VISIBLE);

                head_imgcard.setVisibility(View.GONE);//新添加的头像
                head_name.setVisibility(View.GONE);

                ToastUtils.showToast(MainActivity.this, "数据同步失败");
                //progressDlg.dismiss();
              //  SVProgressHUD.dismiss(MainActivity.this);
               // SVProgressHUD.showErrorWithStatus(MainActivity.this,"加载失败...");
            }
        });
    }

    //加载名片数据
    private void showBusinessCard() {
        mName = (TextView) findViewById(R.id.name);
        mCellphone = (TextView) findViewById(R.id.cellphone);
        mEMail = (TextView) findViewById(R.id.email);
        mCompany = (TextView) findViewById(R.id.company);
        mMyHead = (ImageView) findViewById(R.id.head_img);

        mCellphoneImg = (ImageView) findViewById(R.id.cellphone_img);
        mEMailImg = (ImageView) findViewById(R.id.email_img);
        mCompanyImg = (ImageView) findViewById(R.id.company_img);


        mName.setText(mBusinessCard.getName());

        String strMobile = mBusinessCard.getMobile();
        if (strMobile == null || "".equals(strMobile)) {
            mCellphoneImg.setVisibility(View.INVISIBLE);
            mCellphone.setText("");
        } else {
            mCellphoneImg.setVisibility(View.VISIBLE);
            mCellphone.setText(strMobile);
        }

        String strEmail = mBusinessCard.getEmail();
        if (strEmail == null || "".equals(strEmail)) {
            mEMailImg.setVisibility(View.INVISIBLE);
            mEMail.setText("");
        } else {
            mEMailImg.setVisibility(View.VISIBLE);
            mEMail.setText(strEmail);
        }

        String strCompany = mBusinessCard.getCompany();
        if (strCompany == null || "".equals(strCompany)) {
            mCompanyImg.setVisibility(View.INVISIBLE);
            mCompany.setText("");
        } else {
            mCompanyImg.setVisibility(View.VISIBLE);
            mCompany.setText(strCompany);
        }


        //获取身份证信息设置 认证按钮状态
        Realm realm = Realm.getDefaultInstance();
        IdCard idCard = realm.where(IdCard.class).equalTo("uid", mStrUserId).findFirst();
        realm.close();

        if (idCard == null) {
            mUnVerity.setVisibility(View.VISIBLE);
        } else {
            mUnVerity.setVisibility(View.GONE);
        }
//            File tempFile = new File(Environment.getExternalStorageDirectory(), "head.png");
//            //  cropRawPhoto(Uri.fromFile(tempFile));//原来要用的工具类
//
//            String filePath = ImageUtils.scaleSaveBitmap(MainActivity.this, tempFile.getAbsolutePath());
//            //setImageToHeadView(filePath);
//            Bitmap photo = BitmapFactory.decodeFile(filePath);
//            mMyHead.setImageBitmap(photo);
        Glide.with(this).load(ConstantUitls.REQUEDT_IMG_URL +mBusinessCard.getHeadImg()).transform(new GlideCircleTransform(this)).into(head_imgcard);//加载圆角图片


         // Bitmap bitmap=Glide.with(this).load(ConstantUitls.REQUEDT_IMG_URL + mBusinessCard.getHeadImg()).into(mMyHead);

//        Bitmap  bitmap = Glide.with(this)
//                .load(ConstantUitls.REQUEDT_IMG_URL + mBusinessCard.getHeadImg())
//                .asBitmap()
//                .into(head_imgcard).get();
        //   Glide.with(this).load(ConstantUitls.REQUEDT_IMG_URL +mBusinessCard.getHeadImg()).into(head_imgcard);
    }

    /**
     * 检查设备是否存在SDCard的工具方法
     */
    public static boolean hasSdcard() {
        String state = Environment.getExternalStorageState();
        return state.equals(Environment.MEDIA_MOUNTED);
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (popupWindow != null && popupWindow.isShowing()) {
            popupWindow.dismiss();
            return true;
        }

        return super.dispatchKeyEvent(event);
    }


    private void updateApp()
    {
        HttpParams params = new HttpParams();
        params.put("type", "1");
        MyHttpsUtils.post(ConstantUitls.REQUEDT_URL + ConstantUitls.THELATESTVERSION, params, new MyHttpsUtils.ResultCallback()
        {
            @Override
            public void onSuccess(String response)
            {
                try
                {
                    JSONObject mjson = new JSONObject(response);
                    JSONObject mdata = mjson.getJSONObject("results");
                    if (mdata.getString("version").equals(getVersion()))
                    {
                        //ToastUtils.showToast(MainActivity.this, "你已经是最新版本！");
                    } else
                    {
                        mStrDownLoadUrl = ConstantUitls.REQUEDT_URL + mdata.getString("downUrl");
                        UpdateDialogFragment updateDialogFragment = new UpdateDialogFragment();
                        updateDialogFragment.show(getFragmentManager(), "");
                    }
                } catch (JSONException e)
                {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(String failReason)
            {
                ToastUtils.showToast(MainActivity.this, failReason);
            }
        });
    }
    //获取当前版本的版本号

    private String getVersion()
    {
        try
        {
            PackageManager packageManager = getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(getPackageName(), 0);
            return packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e)
        {
            e.printStackTrace();
            return "版本号未知";
        }
    }

    @Override
    public void onUpdateAppListener(boolean update)
    {
        if (update)
        {
            Intent intent = new Intent(this, DownLoadService.class);
            intent.putExtra("URL", mStrDownLoadUrl);
            this.startService(intent);
        }
    }

    /**
     * 下载头像并保存到sd卡上
     */
    public void updatefile(){
        final String url_head=ConstantUitls.REQUEDT_IMG_URL+mIdCard.getCompareImg();
        new Thread(new Runnable() {
            @Override
            public void run() {
    OkHttpClient okHttpClient=new OkHttpClient();
    Request request = new Request.Builder().url(url_head).build();

    okHttpClient.newCall(request).enqueue(new Callback() {

        @Override
        public void onFailure(Call call, IOException e) {
            Log.d("h_bl", "onFailure");
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            InputStream is = null;
            byte[] buf = new byte[2048];
            int len = 0;
            FileOutputStream fos = null;
            try {
                is = response.body().byteStream();
                long total = response.body().contentLength();
                String head=ImageUtils.getScaleSavePath(MainActivity.this);
               // String head=UriUtil.getBitmapFilePath(MainActivity.this,"head.jpg");
                fos = new FileOutputStream(head);
                long sum = 0;
                while ((len = is.read(buf)) != -1) {
                    fos.write(buf, 0, len);
                    sum += len;
                    int progress = (int) (sum * 1.0f / total * 100);
                    Log.d("h_bl", "progress=" + progress);
//                    Message msg = mHandler.obtainMessage();
//                    msg.what = 1;
//                    msg.arg1 = progress;
//                    mHandler.sendMessage(msg);
                }
                fos.flush();

                Log.d("h_bl", "文件下载成功");
            } catch (Exception e) {
                Log.d("h_bl", "文件下载失败");
            } finally {
                try {
                    if (is != null)
                        is.close();
                } catch (IOException e) {
                }
                try {
                    if (fos != null)
                        fos.close();
                } catch (IOException e) {
                }
            }
        }
    });
            }
        }).start();
    }

}
